<template>
  <el-card shadow="never">
    <!-- 新增刷新 -->
    <ListHeader @create="handleCreate" @refresh="getData"></ListHeader>

    <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
      <el-table-column label="優惠價名稱">
        <template #default="{ row }">
          <div
            class="border border-dashed py-2 px-4 rounded w-[350px]"
            :class="row.statusText == '領取中' ? 'active' : 'inactive'"
          >
            <h5 class="font-bold text-shadow-md">{{ row.name }}</h5>
            <small>{{ row.start_time }} ~ {{ row.end_time }}</small>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="statusText" label="狀態" />
      <el-table-column prop="statusText" label="優惠">
        <template #default="{ row }">
          {{
            row.type == 10
              ? "满减" + row.money
              : row.type == 20
              ? "满折" + row.money
              : row.type == 30
              ? "立折" + row.money
              : "立减" + row.money
          }}
          <!-- {{ row.type == 10 ? "￥" + row.money : row.money + "折" }} -->
        </template>
      </el-table-column>
      <el-table-column prop="integral" label="兌換積分" />
      <el-table-column prop="desc" label="使用說明" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" text type="primary" @click="handleEdit(row)"
            >修改</el-button
          >
          <el-button
            text
            type="primary"
            v-if="row.statusText == '未開始'"
            size="small"
            @click="handleEdit(row)"
            >修改
          </el-button>
          <el-popconfirm
            title="是否要删除?"
            v-if="row.statusText != '領取中'"
            confirm-button-text="確定"
            cancel-button-text="取消"
            @confirm="handleDelete(row.id)"
          >
            <template #reference>
              <el-button class="!m-0" text type="primary" size="small"
                >删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-center mt-4">
      <el-pagination
        background
        layout="prev,pager, next"
        :total="total"
        :current-page="curpage"
        @current-change="getData"
        :page-size="limit"
      />
    </div>

    <FormDrawer ref="formDrawerRef" @submit="handleSubmit" :title="drawerTitle">
      <el-form ref="formRef" :model="form" label-width="100px">
        <el-form-item label="優惠券名稱" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="兌換所需積分">
          <el-input-number v-model="form.integral" :min="1" />
        </el-form-item>
        <el-form-item label="類型">
          <el-radio-group v-model="form.type" prop="type">
            <el-radio :label="10" border size="default">滿減</el-radio>
            <el-radio :label="20" border size="default">滿折</el-radio>
            <el-radio :label="30" border size="default">立折</el-radio>
            <el-radio :label="40" border size="default">立減</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="面值">
          <el-input-number v-model="form.money" :min="1" />
        </el-form-item>

        <el-form-item label="兌換次數">
          <el-input-number v-model="form.num" :min="1" />
        </el-form-item>

        <el-form-item label="狀態">
          <el-select v-model="form.status" placeholder="請選擇">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="庫存">
          <el-input-number v-model="form.stock" :min="1" />
        </el-form-item>

        <el-form-item label="最低使用價格" prop="condition">
          <el-input-number v-model="form.condition" :min="1" />
        </el-form-item>

        <el-form-item label="活動時間">
          <el-date-picker
            v-model="timerange"
            :editable="false"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="To"
            start-placeholder="開始時間"
            end-placeholder="結束時間"
          />
        </el-form-item>

        <el-form-item label="使用說明">
          <el-input v-model="form.desc" type="textarea" />
        </el-form-item>
      </el-form>
    </FormDrawer>
  </el-card>
</template>

<script setup>
import { get } from "lodash";
import { ref, reactive, computed } from "vue";
import {
  getCoupon,
  createCoupon,
  updateCoupon,
  deleteCoupon,
} from "~/api/coupon.js";
import { useInitTable, useInitForm } from "~/composables/useCommon.js";
import FormDrawer from "../../components/FormDrawer.vue";
import ListHeader from "~/components/ListHeader.vue";
import { toast } from "../../composables/util";

const {
  searchForm,
  resetSearchForm,
  tableData,
  loading,
  curpage,
  total,
  limit,
  getData,
  handleDelete,
} = useInitTable({
  searchForm: {
    keyword: "",
  },
  getList: getCoupon,
  delete: deleteCoupon,
  onGetListSuccess: (res) => {
    total.value = res.total;
    tableData.value = res.data.map((o) => {
      o.statusText = formatStatus(o);

      return o;
    });
  },
});

function formatStatus(row) {
  let s = "領取中";
  let start_time = new Date(row.start_time).getTime();
  let now = new Date().getTime();
  let end_time = new Date(row.end_time).getTime();
  if (start_time > now) {
    s = "未開始";
  } else if (end_time < now) {
    s = "已結束";
  } else if (row.status == 0) {
    s = "失效";
  }
  return s;
}

const {
  formDrawerRef,
  formRef,
  form,
  rules,
  drawerTitle,
  handleSubmit,
  handleCreate,
  handleEdit,
} = useInitForm({
  form: {
    name: "",
    type: 10,
    money: null,
    condition: null,
    start_time: "",
    end_time: "",
    status: 1,
    desc: "",
    stock: 1,
    num: 1,
    integral: 1,
  },
  rules: {
    name: [{ required: true, message: "優惠券不能为空", trigger: "blur" }],
  },
  getData,
  update: updateCoupon,
  create: createCoupon,
  beforeSubmit: (f) => {
    if (typeof f.start_time != Number) {
      f.start_time = new Date(f.start_time).getTime() / 1000;
    }
    if (typeof f.end_time != Number) {
      f.end_time = new Date(f.end_time).getTime() / 1000;
    }
    return f;
  },
});

const timerange = computed({
  get() {
    return form.start_time && form.end_time
      ? [form.start_time, form.end_time]
      : [];
  },
  set(val) {
    form.start_time = val[0];
    form.end_time = val[1];
  },
});

const handleLose = (id) => {
  updateCoupon(id, { status: 0 }).then((res) => {
    toast("操作成功");
    getData();
  });
};
</script>

<style scoped>
.active {
  @apply border-rose-200 bg-rose-50 text-red-400;
}

.inactive {
  @apply border-gray-200 bg-gray-50 text-gray-400;
}
</style>
